<?php
App::uses('AppController', 'Controller');
App::uses('Xml', 'Utility');
/**
 * Domains Controller
 *
 * @property Domain $Domain
 */
class DomainsController extends AppController {
	
	public $helpers = array('Cksource','FileUpload.FileUpload');
	public $components = array('FileUpload.FileUpload');
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->FileUpload->uploadDir('files'.DS.'upload'.DS.'images');
	}
	
/**
 * index method
 *
 * @return void
 */
	public function index() {
		$options = array();
		if ($this->request->is('post')) {
			if(isset($this->request->data['Domain']['project_id']) && $this->request->data['Domain']['project_id']!= ""){
				$options['joins'] = array(
				    array('table' => 'domains_projects',
				        'alias' => 'DomainsProject',
				        'type' => 'inner',
				        'conditions' => array(
				            'Domain.id = DomainsProject.domain_id'
				        )
				    ),
				    array('table' => 'projects',
				        'alias' => 'Project',
				        'type' => 'inner',
				        'conditions' => array(
				            'DomainsProject.project_id = Project.id'
				        )
				    )
				);
				$options['conditions'] = array(
				    'Project.id' => $this->request->data['Domain']['project_id']
				);
			}
			$this->passedArgs['project'] = $this->request->data['Domain']['project_id'];
			$this->paginate = $options;
		}else{
			if(isset($this->passedArgs['project']) && !empty($this->passedArgs['project'])){
				$options['joins'] = array(
				array('table' => 'domains_projects',
								        'alias' => 'DomainsProject',
								        'type' => 'inner',
								        'conditions' => array(
								            'Domain.id = DomainsProject.domain_id'
										)
				),
				array('table' => 'projects',
								        'alias' => 'Project',
								        'type' => 'inner',
								        'conditions' => array(
								            'DomainsProject.project_id = Project.id'
										)
					)
				);
				$options['conditions'] = array(
								    'Project.id' => $this->passedArgs['project']
				);
				$this->paginate = $options;
			}
		}
		
		$this->Domain->recursive = 1;		
		$domains = $this->paginate();
		$this->loadModel('Project');
		$projects = $this->Project->find('list');
		$this->set(compact('projects','domains'));
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Domain->id = $id;

		if (!$this->Domain->exists()) {
			throw new NotFoundException(__('Invalid domain'));
		}
		
		if(!$this->Domain->userAccess($this->Session->read('Auth.User'),'domain_id',$id,'DomainsUser')){
			throw new NotFoundException(__('You do not have permission to access this page'));
		}
		
		if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])){
			// dodajemy do domeny
			$this->Domain->Project->id = $this->passedArgs['p'];
			if ($this->Domain->Project->exists()) {
				$data['Project']['project_id'] = $this->passedArgs['p'];
				$this->request->data = $data;
			}
		}
		
		
		$this->loadModel('Article');
		$options['conditions'] = array('Article.domain_id'=>$id,'Article.status'=>1);
		$articles_ = $this->Article->find('all',$options);
		if(is_array($articles_)){
			foreach ($articles_ as $key => $article) {
				$articles[$article['Article']['menuses_id']][$article['Article']['id']] = array('name'=>$article['Article']['name'],'id'=>$article['Article']['id'],'description'=>$article['Article']['descriptions']);
			}
		}

		$options['joins'] = array(
		array('table' => 'domains',
							        'alias' => 'Domain',
							        'type' => 'inner',
							        'conditions' => array(
							            'Submenu.domain_id = Domain.id'
		)
		),
			
		);
		
		$options['conditions'] = array(
						 'Domain.id' => $id
		);
		
		
		
// 		$this->loadModel('Submenu');
// 		$this->Submenu->recursive = -1;
// 		$submenuses = $this->Submenu->find('threaded',$options);
// 		$submenus_combobox = $this->treeForCombobox($submenuses,'Submenu',array('model'=>'Submenu','name'=>'name'),false);

		
		if(isset($this->passedArgs['d'])){
			$this->Domain->filter($this->passedArgs['d']);
		}else{
			$this->Domain->filter();
		}	
		
		
		$domain = $this->Domain->read(null, $id);

		if(isset($this->passedArgs['d']) && $this->passedArgs['d'] == 'menus' || isset($this->passedArgs['d']) && $this->passedArgs['d'] == 'articles'){
			$options['joins'] = array(
			    array('table' => 'domains_menuses',
			        'alias' => 'DomainsMenus',
			        'type' => 'inner',
			        'conditions' => array(
			            'Menus.id = DomainsMenus.menus_id'
			        )
			    ),
			    array('table' => 'domains',
			        'alias' => 'Domain',
			        'type' => 'inner',
			        'conditions' => array(
			            'DomainsMenus.domain_id = Domain.id'
			        )
			    )
			);
			$options['conditions'] = array(
			    'Domain.id' => $id
			);
			$options['order'] = array(
					    'Menus.lft'
			);
			
			$this->loadModel('Menus');
			$menuses = $this->Menus->find('threaded',$options);
			$menuses = $this->treeForCombobox($menuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
			$menuses_combobox = $menuses;		
		
			$options['fields'] = array('Menus.id','Menus.status');
			$statuses = $this->Menus->find('list',$options);
			
			$options['fields'] = array('Menus.id','Menus.position');
			$positions = $this->Menus->find('list',$options);
			
				
			if(is_array($menuses)){
				foreach ($menuses as $key => $name) {
					$article = (isset($articles[$key])) ? $articles[$key] : null;  
					$menuses[$key] = array('id'=>$key,'name'=>$name,'status'=>$statuses[$key],'position'=>$positions[$key],'article'=>$article);
				}
			}
		
		}
		
		if(isset($this->passedArgs['d']) && $this->passedArgs['d'] == 'jobs'){
			/*JOBS*/
			$options_jobs['joins'] = array(
					array('table' => 'domains_jobs',
							'alias' => 'DomainsJob',
							'type' => 'inner',
							'conditions' => array(
									'Job.id = DomainsJob.job_id'
							)
					),
					array('table' => 'domains',
							'alias' => 'Domain',
							'type' => 'inner',
							'conditions' => array(
									'DomainsJob.domain_id = Domain.id'
							)
					)
			);
		
			$options_jobs['conditions'] = array(
					'Domain.id' => $id
			);
		
			$this->loadModel('User');
			$options_users['fields'] = array('User.id','User.username');
			$users = $this->User->find('list',$options_users);
			
			$this->loadModel('Group');
			$options_group['fields'] = array('Group.id','Group.name');
			$groups = $this->Group->find('list',$options_group);
			
			$this->loadModel('Job');
			$jobs = $this->Job->find('threaded',$options_jobs);
			$jobs_ = $this->Job->find('all',$options_jobs);
			$jobs = $this->treeForCombobox($jobs,'Job',array('model'=>'Job','name'=>'description'),false);
			if(is_array($jobs_)){
				foreach ($jobs_ as $key => $job_) {
					$name = (isset($jobs[$job_['Job']['id']])) ? $jobs[$job_['Job']['id']] : null;
					$group = (isset($groups[$job_['Job']['group_id']])) ? __('Group').': '.$groups[$job_['Job']['group_id']] : null;
					$jobs[$job_['Job']['id']] = array('id'=>$job_['Job']['id'],'description'=>$name,'status'=>$job_['Job']['status'],'priorytet'=>$job_['Job']['priorytet'],'zlecajacy'=>$users[$job_['Job']['user_id']],'date_end'=>$job_['Job']['date_end'],'wykonawcy'=>$job_['User'],'group'=>$group);
				}
			}
		}
		
		if(isset($this->passedArgs['d']) && $this->passedArgs['d'] == 'lastminute'){
			$options['joins'] = array(
					array('table' => 'domains_sources',
							'alias' => 'DomainsSource',
							'type' => 'inner',
							'conditions' => array(
									'Source.id = DomainsSource.source_id'
							)
					),
					array('table' => 'domains',
							'alias' => 'Domain',
							'type' => 'inner',
							'conditions' => array(
									'DomainsSource.domain_id = Domain.id'
							)
					)
			);
			$options['conditions'] = array(
					'Domain.id' => $id
			);
			$options['order'] = array(
					'Source.name'
			);
				
			$this->loadModel('Source');
			$sources = $this->Source->find('all',$options);
		
		
		}

		$menu_positions = Configure::read('Config.menu_positions');
		$setting_groups = Configure::read('Config.cfg_groups');
		$this->set(compact('domain','menuses','menuses_combobox','submenuses','submenus_combobox','menu_positions','setting_groups','jobs','sources'));

	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->Domain->create();
			if ($this->Domain->save($this->request->data)) {
				$this->Session->setFlash(__('The domain has been saved'));
				if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])) $this->redirect(array('controller'=>'projects','action' =>'view',$this->passedArgs['p']));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The domain could not be saved. Please, try again.'));
			}
		}
		
		if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])){
			// dodajemy do domeny
			$this->Domain->Project->id = $this->passedArgs['p'];
			if ($this->Domain->Project->exists()) {
				$data['Project']['project_id'] = $this->passedArgs['p'];
				$this->request->data = $data;
			}
		}
		
		$servers = $this->Domain->Server->find('list');
		$serversips = $this->Domain->Serversip->find('list');
		$menuses = $this->Domain->Menus->find('list');
		$projects = $this->Domain->Project->find('list');
		$users = $this->Domain->User->find('list');
		$this->set(compact('servers', 'serversips', 'menuses', 'projects', 'users'));
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->Domain->id = $id;
		if (!$this->Domain->exists()) {
			throw new NotFoundException(__('Invalid domain'));
		}
		if(!$this->Domain->userAccess($this->Session->read('Auth.User'),'domain_id',$id,'DomainsUser')){
			throw new NotFoundException(__('You do not have permission to access this page'));
		}
		
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Domain->save($this->request->data)) {
				$this->Session->setFlash(__('The domain has been saved'));
				if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])) $this->redirect(array('controller'=>'projects','action' =>'view',$this->passedArgs['p']));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The domain could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Domain->read(null, $id);
		}
		
		if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])){
			// dodajemy do domeny
			$this->Domain->Project->id = $this->passedArgs['p'];
			if ($this->Domain->Project->exists()) {
				$this->request->data['Project']['project_id'] = $this->passedArgs['p'];
			}
		}
		
		$servers = $this->Domain->Server->find('list');
		$serversips = $this->Domain->Serversip->find('list');
		$menuses = $this->Domain->Menus->find('list');
		$projects = $this->Domain->Project->find('list');
		$users = $this->Domain->User->find('list');
		$this->set(compact('servers', 'serversips', 'menuses', 'projects', 'users'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		if(!$this->Domain->userAccess($this->Session->read('Auth.User'),'domain_id',$id,'DomainsUser')){
			throw new NotFoundException(__('You do not have permission to access this page'));
		}
		
		$this->Domain->id = $id;
		if (!$this->Domain->exists()) {
			throw new NotFoundException(__('Invalid domain'));
		}
		if ($this->Domain->delete()) {
			$this->Session->setFlash(__('Domain deleted'));
			if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])) $this->redirect(array('controller'=>'projects','action' =>'view',$this->passedArgs['p']));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Domain was not deleted'));
		if(isset($this->passedArgs['p']) && !empty($this->passedArgs['p'])) $this->redirect(array('controller'=>'projects','action' =>'view',$this->passedArgs['p']));
		$this->redirect(array('action' => 'index'));
	}
	
	/**
	 * Export bazy z Panela do local database for domain
	 * @param unknown_type $id
	 * @throws NotFoundException
	 * @return unknown
	 */
	public function update($id = null){
		$this->Domain->id = $id;
		if (!$this->Domain->exists()) {
			throw new NotFoundException(__('Invalid domain'));
		}
		if(!$this->Domain->userAccess($this->Session->read('Auth.User'),'domain_id',$id,'DomainsUser')){
			throw new NotFoundException(__('You do not have permission to access this page'));
		}

		/* Domain */
		$this->Domain->recursive = -1;
		$domain = $this->Domain->read(null, $id);
		$data_domain['update']['Domain'] = $domain;
		
		$domain_update_url = 'http://'.$domain['Domain']['name'].'/update/domain';

		$models = array(				
				'Configuration'=>array('conditions' => array('Configuration.domain_id' => $id )),
// 				'Competition'=>array('conditions' => array('Competition.domain_id' => $id )),							
				'Menus'=>array(
						'joins'=>array(
								array('table' => 'domains_menuses',
										'alias' => 'DomainsMenus',
										'type' => 'inner',
										'conditions' => array(
												'Menus.id = DomainsMenus.menus_id'
										)
								),
								array('table' => 'domains',
										'alias' => 'Domain',
										'type' => 'inner',
										'conditions' => array(
												'DomainsMenus.domain_id = Domain.id'
										)
								)
						),
						'conditions' => array(
								'Domain.id' => $id,
								'Menus.status' => 1
						),
						'order' => array('Menus.lft')
				),
				'DomainsMenus'=>array('conditions' => array('DomainsMenus.domain_id' => $id )),
				'Article'=>array('conditions' => array('Article.domain_id' => $id )),
				'Upload'=>array(
						'joins'=>array(
								array('table' => 'articles_uploads',
										'alias' => 'ArticlesUpload',
										'type' => 'inner',
										'conditions' => array(
												'Upload.id = ArticlesUpload.upload_id'
										)
								),
								array('table' => 'articles',
										'alias' => 'Article',
										'type' => 'inner',
										'conditions' => array(
												'ArticlesUpload.article_id = Article.id'
										)
								)
						),
						'conditions' => array(
								'Article.domain_id' => $id
						)
				),
				'Upload'=>array('conditions' => array('Upload.domain_id' => $id )),
				'ArticlesUpload'=>array(
						'joins'=>array(
								array('table' => 'articles',
										'alias' => 'Article',
										'type' => 'inner',
										'conditions' => array(
												'ArticlesUpload.article_id = Article.id'
										)
								)
						),
						'conditions' => array(
								'Article.domain_id' => $id
						)
				),				
				
				'PostsArticle'=>array(
						'joins'=>array(
									array('table' => 'articles',
											'alias' => 'Article',
											'type' => 'inner',
											'conditions' => array(
													'PostsArticle.article_id = Article.id'
											)
									)
							),
							'conditions' => array(
									'Article.domain_id' => $id
							)
						),
				'Post'=>array('conditions' => array('Post.domain_id' => $id )),
				'Comment'=>array('conditions' => array('Comment.domain_id' => $id )),
				'ArticlesComment'=>array(
						'joins'=>array(
								array('table' => 'articles',
										'alias' => 'Article',
										'type' => 'inner',
										'conditions' => array(
												'ArticlesComment.article_id = Article.id'
										)
								)
						),
						'conditions' => array(
								'Article.domain_id' => $id
						)
				)
// 				'Rating'
						
				);
		
			
		$xmlObject = Xml::fromArray($data_domain, array('format' => 'tags','encoding'=>'utf8'));
		$data = urlencode($xmlObject->asXML());
			
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $domain_update_url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,"updates=$data");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$results = curl_exec($ch);
		curl_close($ch);
		
		foreach ($models as $model => $options) {
			$data = $this->getData($model, $options, array());
			$xmlObject = Xml::fromArray($data, array('format' => 'tags','encoding'=>'utf8'));
			$data = urlencode($xmlObject->asXML());
					
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $domain_update_url);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS,"updates=$data");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$results = curl_exec($ch);
			curl_close($ch);
		}
		
		$this->redirect(array('controller'=>'domains','action' =>'view',$id));
// 		$this->redirect(array('action' => 'index'));

	}
	
	private function getData($model=null, $options=array(), $data=null){
	
		$this->loadModel($model);
		$this->$model->recursive = -1;
		$d = $this->$model->find('all',$options);
		$data['update'][$model] = $d;
// 		debug($data);
		return $data;
	}
}
